package cn.edu.zut.cs.WebSocket;

import cn.edu.zut.cs.Model.User;
import cn.edu.zut.cs.Utils.MessageUtils;
import cn.edu.zut.cs.pojo.Message;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat",configurator = HttpSessionConfigurator.class)
public class ChatEndpoint {
    // 存储每个客户端对象对应的ChatEndpoint对象
    private static Map<String, ChatEndpoint> onlineUsers = new ConcurrentHashMap<>();
    //声明session对象，通过给对象可以发送消息给指定用户
    private Session session;
    //声明httpSession对象,在httpSession对象中存储了用户名
    private HttpSession httpSession;

    @OnOpen
    //连接建立时执行
    public void onOpen(Session session, EndpointConfig config){
        //将局部的session对象赋值给成员session
        this.session = session;
        //获取HttpSession对象
        HttpSession httpSession = (HttpSession)config.getUserProperties().get(HttpSession.class.getName());
        this.httpSession = httpSession;

        //从httpSession对象中获取用户名
        User userInfo=(User)httpSession.getAttribute("userInfo");
        String username = userInfo.getNickname();

        //将当前对象存至容器中
        if(username!=null){
            onlineUsers.put(username,this);
            //将当前在线用户名推送给所有的客户端
            //1.获取消息---系统消息
            String message = MessageUtils.getMessage(true,null,null,getNames());
            //2.调用方法进行系统推送
            broadcastAllUsers(message);
        }

    }

    private void broadcastAllUsers(String message){
        //将该消息推送给所有的客户端
        try{
            Set<String> names = onlineUsers.keySet();
            for(String name:names){
                ChatEndpoint chatEndpoint = onlineUsers.get(name);
                chatEndpoint.session.getAsyncRemote().sendText(message);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private Set<String> getNames(){
        return onlineUsers.keySet();
    }

    @OnMessage
    //接收到客户端发送数据时调用
    public void onMessage(String message,Session session){
        try{
            //将message转换成Message对象
            ObjectMapper mapper = new ObjectMapper();
            Message mess = mapper.readValue(message, Message.class);
            //获取收取方用户
            String toName = mess.getToName();
            //获取消息数据
            String data = mess.getMessage();
            //获取当前登录用户
            User userInfo=(User)httpSession.getAttribute("userInfo");
            String username = userInfo.getNickname();
            //获取发送数据方的图片信息
            String img = mess.getImg();
            //获取推送给指定用户的消息格式的数据
            String resultMessage = MessageUtils.getMessage(false,username,img,data);
            //发送数据
            if(isInUsers(toName)){
                onlineUsers.get(toName).session.getBasicRemote().sendText(resultMessage);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public boolean isInUsers(String toName){
        for(String users : onlineUsers.keySet()){
            if(toName.equals(users))
                return true;
        }
        return false;
    }

    @OnClose
    //连接关闭时调用
    public void onClose(Session session){
        User userInfo=(User)httpSession.getAttribute("userInfo");
        String username = userInfo.getNickname();
        if(username!=null){
            //从容器中删除指定用户
            onlineUsers.remove(username);
            //获取推送到消息
            String message = MessageUtils.getMessage(true,null,null,getNames());
            broadcastAllUsers(message);
        }
    }
}
